package com.zyzd.baseretrofit.base.fragment;


import com.zyzd.baseretrofit.bean.remote.ApiResultBean;
import com.zyzd.baseretrofit.net.Api;
import com.zyzd.baseretrofit.net.ApiCallback;
import com.zyzd.baseretrofit.net.HttpResultFunc;
import com.zyzd.baseretrofit.net.RetrofitHelper;
import com.zyzd.baseretrofit.net.UploadApi;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 李宗源 on 2016/11/9.
 */

public abstract class BaseNetFragment<T> extends BaseFragment {


    protected <E> void toSubscribe(Observable<ApiResultBean<E>> observable, Subscriber<E> subscriber) {
        observable.map(new HttpResultFunc<E>())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    protected <E> Observable<E> getObservable(Observable<ApiResultBean<E>> observable) {
        return observable.map(new HttpResultFunc<E>());
    }

    /**
     * 该订阅器，是针对性的
     *
     * @return
     */
    protected Subscriber<T> getSubscriber() {
        return new ApiCall<T>(getSimpleName()) {
            @Override
            public void onSuccess(T model) {
                BaseNetFragment.this.onSuccess(model);
            }
        };
    }

    /**
     * 提高实用性，可以在activity中进行错误处理和完成处理
     *
     * @param <E>
     */
    protected abstract class ApiCall<E> extends ApiCallback<E> {
        protected String tag;

        public ApiCall(String tag) {
            this.tag = tag;
        }

        @Override
        public void onFailure(String msg, int errorCode) {
            BaseNetFragment.this.onRequestFail(msg, errorCode, tag);
        }

        @Override
        public void onFinish() {
            BaseNetFragment.this.onRequestFinish(tag);
        }
    }


    /**
     * 请求完成
     *
     * @param tag
     */
    protected void onRequestFinish(String tag) {
    }

    protected void onRequestFail(String msg, int errorCode, String tag) {
    }

    protected void onSuccess(T t) {
        if (t == null) {
            onDataNull();
        } else {
            parseData(t);
        }
    }

    /**
     * 当返回数据为空时的处理
     */
    protected void onDataNull() {
    }

    /**
     * 数据处理
     *
     * @param t
     */
    protected abstract void parseData(T t);

    /**
     * 普通api
     *
     * @return
     */
    public Api getApi() {
        return RetrofitHelper.getApi();
    }

    /**
     * 上传图片api，特殊情况，因为上传图片api基本路径与普通api不一致
     *
     * @return
     */
    public UploadApi getUploadApi() {
        return RetrofitHelper.getUploadApi();
    }
}
